package cn.shenlong.front.action;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.shenlong.common.Pagination;
import cn.shenlong.portal.domain.EmailConfig;
import cn.shenlong.portal.domain.Member;
import cn.shenlong.portal.domain.MemberCard;
import cn.shenlong.portal.domain.MemberValid;
import cn.shenlong.portal.service.EmailConfigService;
import cn.shenlong.portal.service.MemberCardService;
import cn.shenlong.portal.service.MemberService;
import cn.shenlong.portal.service.MemberValidService;
import cn.shenlong.util.MailUtil;

@Controller
public class Members {
	private static final Logger log = LoggerFactory.getLogger(Members.class);

	@Autowired
	private MemberService memberService;
	
	@Autowired
	private MemberValidService memberValidService;
	
	@Autowired
	private MemberCardService memberCardService;
	
	@Autowired
	private EmailConfigService emailConfigService;

	@RequestMapping(value = "/front/register", method = RequestMethod.GET)
	public String register(HttpServletRequest request, ModelMap model) {
		Object member = request.getSession().getAttribute("login_member");
		if (member != null) {//说明已经登录
//			return "redirect:home.html";
		}
		return "/front/register";

	}
	
	@RequestMapping(value = "/front/membervalid", method = RequestMethod.GET)
	public String membervalid(HttpServletRequest request, ModelMap model,Long memberId) {
		if (memberId == null) {
			return "redirect:home.html";
		}
		model.put("memberId", memberId);
		return "/front/membervalid";

	}

	@RequestMapping(value = "/front/saveMember", method = RequestMethod.POST)
	public String saveMember(Member member,HttpServletRequest request, ModelMap model) {
		try {				
			Long count = memberService.findMemberCountByName(member.getLoginName());
			if (count.longValue() == 0) {
				member.setDataflg(0);				
				memberService.save(member);
				
				MemberValid mv = new MemberValid();
				mv.setMemberId(member.getMemberId());
				mv.setCode(getRadomNumStr(6));
				memberValidService.save(mv);				
				
				String title = "Identifying code";
				String content = mv.getCode();				
				EmailConfig emailConfig = emailConfigService.findByPK(1);
				if (emailConfig != null) {
					if (emailConfig.getEmailTitle() != null && !emailConfig.getEmailTitle().trim().equals("")) {
						title = emailConfig.getEmailTitle();
					}
					String emailContent = emailConfig.getEmailContent();
					if (emailContent != null && !emailContent.trim().equals("") && emailContent.indexOf("IdentifyCodeToReplace") > -1) {
						content = emailContent.replace("IdentifyCodeToReplace", mv.getCode()); 
					}
				}
				
				MailUtil.sendEmail(member.getEmail(), title, content, emailConfig);
				
				if(member != null) model.put("msg", "Success,the identifying code had send to your email,please input your identifying code");
//				ajaxLoginIn(member.getLoginName(), member.getPassword(), request, null);
//				return "redirect:home.html";
				return membervalid(request,model,member.getMemberId());
			} else {
				model.put("msg", "The usename is eixits!");
				return register(request, model);
			}
		} catch (Exception e) {
			model.put("msg", e.getMessage());
			return register(request, model);
		}
	}

	@RequestMapping(value = "/front/validMember", method = RequestMethod.POST)
	public String validMember(MemberValid memberValid,HttpServletRequest request, ModelMap model) {
		try {
			if (memberValid.getMemberId() == null) {
				return "/front/home";
			}
			model.put("memberId", memberValid.getMemberId());
			Pagination p = memberValidService.findMemberValid(memberValid, null, 1, 1);
			if (p.getList() != null && !p.getList().isEmpty()) {
				memberValid = (MemberValid) p.getList().get(0);
				
				Member member = memberService.findMemberByMemberId(memberValid.getMemberId());				
				if (member == null) {
					model.put("msg", "Identifying code is incorrect");
					return "/front/membervalid";
				} else if (member.getDataflg() != null && member.getDataflg().intValue() == 1) {
					return "/front/personal";
				} else {
					member.setDataflg(1);
					memberService.updateMember(member);
					
					request.getSession().setAttribute("login_member", member);
					request.getSession().setAttribute("loginName", member.getLoginName());
					
					memberValidService.deleteMemberValid(new Long[]{memberValid.getId()});
				}
			} else {
				model.put("msg", "Identifying code timeout");
				return "/front/membervalid";
			}
			
			
			return "redirect:/front/personal.html";
		} catch (Exception e) {
			model.put("msg", e.getMessage());
			return "/front/membervalid";
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/front/ajaxLoginName")
	public Map<String, Object> ajaxLoginName(String loginName, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (StringUtil.isBlank(loginName)) {
			resultMap.put("msg", "参数为空");
			return resultMap;
		}
		Long count = memberService.findMemberCountByName(loginName);
		if (count.longValue() == 0) {
			resultMap.put("msg", "true");
		} else {
			resultMap.put("msg", "用户已存在，请重新填写用户名");
		}

		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/front/ajaxPassword")
	public Map<String, Object> ajaxPassword(String password,Long memberId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Member member = memberService.findMemberByMemberId(memberId);
		if (member != null) {
			if (password.equals(member.getPassword())) {
				resultMap.put("msg", "true");
			} else {
				resultMap.put("msg", "The old password is incorrect");
			}
		}

		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/front/ajaxEmail")
	public Map<String, Object> ajaxEmail(String email,Long memberId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Member result = null;
		if (memberId == null) {
			result = memberService.findByEmail(email);
		} else {
			result = memberService.findByEmailIgnoreId(email, memberId);
		}
		
		if (result == null) {
			resultMap.put("msg", "true");
		} else {
			resultMap.put("msg", "The email inputted is exists");
		}

		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/ajaxLoginIn", method = RequestMethod.POST)
	public Map<String, Object> ajaxLoginIn(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtil.isBlank(loginName) || StringUtil.isBlank(password)) {
			resultMap.put("msg", "参数为空");
			return resultMap;
		}
		Member loginMember = memberService.login(loginName, password);
		if (loginMember != null) {
			if (loginMember.getDataflg() != null && loginMember.getDataflg().intValue() == 1) {
				resultMap.put("msg", "true");
				request.getSession().setAttribute("login_member", loginMember);
				request.getSession().setAttribute("loginName", loginMember.getLoginName());
			} else {
				resultMap.put("msg", "id="+loginMember.getMemberId());
			}
		} else {
			resultMap.put("msg", "wrong");
		}

		return resultMap;

	}
	
	@ResponseBody
	@RequestMapping(value = "/ajaxLoginOut", method = RequestMethod.POST)
	public Map<String, Object> ajaxLoginOut(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			request.getSession().removeAttribute("login_member");
			request.getSession().removeAttribute("loginName");
			resultMap.put("msg", "true");
		} catch (Exception e) {
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	
	@RequestMapping(value = "/front/personal", method = RequestMethod.GET)
	public String personal(HttpServletRequest request, ModelMap model) {
		Object member = request.getSession().getAttribute("login_member");
		if (member == null) {//说明未登录
			return "redirect:home.html";
		}
		Long memberId = ((Member)member).getMemberId();
		model.put("member", memberService.findMemberByMemberId(memberId));
		return "/front/personal";
	}
	
	@RequestMapping(value = "/front/memberpwd", method = RequestMethod.GET)
	public String memberpwd(HttpServletRequest request, ModelMap model) {
		Object member = request.getSession().getAttribute("login_member");
		if (member == null) {//说明未登录
			return "redirect:home.html";
		}
		Long memberId = ((Member)member).getMemberId();
		model.put("member", memberService.findMemberByMemberId(memberId));
		return "/front/memberpwd";

	}
	
	@RequestMapping(value = "/front/bindMemberCard", method = RequestMethod.GET)
	public String bindMemberCard(HttpServletRequest request, ModelMap model) {
		Object member = request.getSession().getAttribute("login_member");
		if (member == null) {//说明未登录
			return "redirect:home.html";
		}
		Long memberId = ((Member)member).getMemberId();
		MemberCard memberCard = this.memberCardService.findMemberCardByMemberId(memberId);
		model.put("member", memberService.findMemberByMemberId(memberId));
		model.put("memberCard", memberCard);
		return "/front/bindMemberCard";
	}
	
	@RequestMapping(value = "/front/updateMember", method = RequestMethod.POST)
	public String updateMember(Member member,HttpServletRequest request, ModelMap model) {
		Object memberObj = request.getSession().getAttribute("login_member");
		if (memberObj == null) {//说明未登录
			model.put("msg", "Session timeout,please login again!");			
		} else {
			try {
				memberService.updateMember(member);
				if(member != null) model.put("msg", "success");
				ajaxLoginIn(member.getLoginName(), member.getPassword(), request, null);
			} catch (Exception e) {
				model.put("msg", e.getMessage());
			}
		}
		return "/front/personal";
	}
	
	@RequestMapping(value = "/front/updateMemberPwd", method = RequestMethod.POST)
	public String updateMemberPwd(Member member,HttpServletRequest request, ModelMap model) {
		Object memberObj = request.getSession().getAttribute("login_member");
		if (memberObj == null) {//说明未登录
			model.put("msg", "Session timeout,please login again!");			
		} else {
			try {
				memberService.updateMember(member);
				if(member != null) model.put("msg", "success");
				ajaxLoginIn(member.getLoginName(), member.getPassword(), request, null);
			} catch (Exception e) {
				model.put("msg", e.getMessage());
			}
		}
		return "/front/memberpwd";
	}
	
	public static String getRadomNumStr(int length) {
    	Random rd = new Random();
    	StringBuffer sb = new StringBuffer();
    	for (int i=0;i<length;i++) {
    		sb.append(rd.nextInt(10));
    	}
    	return sb.toString();
    }
	
	@ResponseBody
	@RequestMapping(value = "/ajaxMemberCode")
	public Map<String, Object> ajaxMemberCode(String memberCardCode, Long memberId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (StringUtil.isBlank(memberCardCode)) {
			resultMap.put("msg", "参数为空");
			return resultMap;
		}
		
		MemberCard memberCard = memberCardService.findMemberCardByCode(memberCardCode);
		if (memberCard == null) {
			resultMap.put("msg", "err1");//不存在
		} else {
			if (memberCard.getMemberId() == null) {
				resultMap.put("msg", "true");//ok
			} else {
				resultMap.put("msg", "err2");//其他用户绑定了
			}
		}

		return resultMap;
	}
	
	@RequestMapping(value = "/front/saveBindMemberCard", method = RequestMethod.POST)
	public String saveBindMemberCard(Long memberId,String memberCardCode,HttpServletRequest request, ModelMap model) {
		Object memberObj = request.getSession().getAttribute("login_member");
		if (memberObj == null) {//说明未登录
			model.put("msg", "Session timeout,please login again!");
			return "/front/bindMemberCard";		
		} else {
			try {
				memberService.bingMemberCard(memberId, memberCardCode);
			} catch (Exception e) {
				model.put("msg", e.getMessage());
				return "/front/bindMemberCard";
			}
		}
		return "redirect:/front/bindMemberCard.html";
	}
	
	@ResponseBody
	@RequestMapping(value = "/ajaxBecomeMember")
	public Map<String, Object> ajaxBecomeMember(Long memberId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (memberId == null) {
			resultMap.put("msg", "参数为空");
			return resultMap;
		}
		
		MemberCard memberCard = memberCardService.findMemberCardByMemberId(memberId);
		if (memberCard == null) {
			resultMap.put("msg", "err1");//未绑定会员卡
		} else {
			if (memberCard.getIsValid() != null && memberCard.getIsValid() == true) {//已审核
				resultMap.put("msg", "true");//ok
			} else {
				resultMap.put("msg", "err2");//已绑定，未审核
			}
		}
		return resultMap;
	}
}
